package com.aqumon.www.controller;

import com.aqumon.www.entity.request.auth.UserLoginReq;
import com.aqumon.www.entity.request.auth.UserRegisterReq;
import com.aqumon.www.entity.response.controller.Response;
import com.aqumon.www.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * Created by didi on 2021/4/22.
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Resource
    UserService userService;
    /**
     * 用户注册
     * @param req
     * @param request
     * @param response
     * @return
     */
//    @PostMapping("/register")
    public Response<?> register(@RequestBody UserRegisterReq req, HttpServletRequest request, HttpServletResponse response) {
        return Response.success(userService.register(req,request,response));
    }

    /**
     * 用户登录
     * @param req
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/login")
    public Response<?> login(@RequestBody UserLoginReq req, HttpServletRequest request, HttpServletResponse response,
                             @Value("${ad.baseDN}") String baseDN,  @Value("${ad.timeout}") String timeout,
                             @Value("${ad.adHost}") String adHost, @Value("${ad.adNormalPort}") int adNormalPort,
                             @Value("${ad.adminName}") String adminName, @Value("${ad.adminPassWord}")  String adminPassWord) {
        int data = 0;
        try {
            data = userService.login(req,request,response, baseDN, adHost, adNormalPort, adminName, adminPassWord, timeout);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (Integer.valueOf(data).equals(0)) {
            return Response.success(data);
        } else if (Integer.valueOf(data).equals(10009999)) {
            return Response.Failed("认证异常，可能原因：连接超时", data);
        } else {
            return Response.Failed("用户名或密码错误", data);
        }
//        return Response.success(userService.login(req,request,response, baseDN, adHost, adNormalPort, adminName, adminPassWord));
    }

    @PostMapping("/quit")
    public Response<?> logout(HttpServletRequest request,HttpServletResponse response) {
        return Response.success(userService.logout(request, response));
    }
}
